package pkg

import (
	"bunker/pkg/myfs"
	"bunker/pkg/pb"
	"context"
	"fmt"
	"log"
	"net"

	"google.golang.org/grpc"
	"google.golang.org/protobuf/proto"
)

type Server struct {
	pb.UnimplementedBunkerServer
	root *myfs.DirInode
	key  []byte
	sign *Sign
}

// 保存文件
func (sf *Server) SaveFile(_ context.Context, req *pb.Request) (*pb.ErrResp, error) {
	if !sf.sign.Verify(sf.key, req.Data, req.Sign) {
		return &pb.ErrResp{
			Code:    1,
			Message: "sgin verify failed",
		}, nil
	}

	var data pb.Data_SaveFile
	err := proto.Unmarshal(req.Data, &data)
	if err != nil {
		return &pb.ErrResp{
			Code:    2,
			Message: "unmarshal failed",
		}, nil
	}
	fmt.Println("save file:", data.FileName)

	ok := sf.root.SaveFile(data.FileName, data.FileContent, data.Force)
	if !ok {
		return &pb.ErrResp{
			Code:    3,
			Message: "save file failed",
		}, nil
	}

	return &pb.ErrResp{
		Code:    0,
		Message: "ok",
	}, nil
}

// 启动grpc服务
func StartServer(root *myfs.DirInode, socketPath string, key []byte) {
	if len(key) == 0 {
		return
	}

	// 创建监听器
	listener, err := net.Listen("unix", socketPath)
	if err != nil {
		GS.Cancel()
		fmt.Printf("failed to listen on socket: %v", err)
		return
	}

	// 注册清理函数
	GS.RegisterCleanFunc(func() {
		err := listener.Close()
		log.Printf("close listener: %v", err)
	})

	// 创建 gRPC 服务器
	grpcServer := grpc.NewServer()

	// 注册您的 gRPC 服务（假设已经定义并实现了服务）
	pb.RegisterBunkerServer(grpcServer, &Server{root: root, key: key})

	// 启动 gRPC 服务
	fmt.Println("Server listening on", socketPath)
	if err := grpcServer.Serve(listener); err != nil {
		log.Printf("failed to serve: %v", err)
	}
}
